package com.gdpu.liou.symphonyserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import com.gdpu.liou.symphonyserver.mapper.SongMapper;
import com.gdpu.liou.symphonyserver.entity.Song;
import com.gdpu.liou.symphonyserver.entity.respose.Response;
import com.gdpu.liou.symphonyserver.service.SongService;
import com.gdpu.liou.symphonyserver.common.utils.PagingUtil;
import com.gdpu.liou.symphonyserver.common.utils.FileUpload;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;


/**
 * 歌曲service实现类
 *
 * @author Fox
 */
@Service
@Slf4j
public class SongServiceImpl implements SongService {
    @Autowired
     SongMapper songMapper;
    @Autowired
    FileUpload fileUpload;
    private final StringRedisTemplate stringRedisTemplate;


    public SongServiceImpl(SongMapper songMapper, StringRedisTemplate stringRedisTemplate) {
        this.songMapper = songMapper;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 添加歌曲
     */
    @Override
    public boolean insertSong(Song song) {
        return songMapper.insertSong(song);
    }

    @Override
    public boolean insertCollectSong(Integer consumerId, Integer songId) {
        int i = songMapper.selectCollectSongIsExist(consumerId, songId);
        if (i == 0) {
            songMapper.insertCollectSong(consumerId, songId);
            return true;
        }
        songMapper.deleteCollectSong(consumerId, songId);
        return false;
    }


    /**
     * 删除歌手
     */
    @Override
    public boolean deleteSong(Integer id) {
        return songMapper.deleteSongBySongId(id) > 0;
    }



    /**
     * 修改歌曲
     */
    @Override
    public void updateSong(HttpServletRequest request) {
        //接受singer数据
        String id = request.getParameter("id").trim();
        String name = request.getParameter("name").trim();
        String introduction = request.getParameter("introduction").trim();
        String lyric = request.getParameter("lyric").trim();
        //将数据封装成Song对象
        Song song = new Song();
        song.setId(Integer.valueOf(id));
        song.setName(name);
        song.setIntroduction(introduction);
        song.setLyric(lyric);
        songMapper.updateSong(song);
    }

    /**
     * 分页查询歌手的所有歌曲：根据歌手id
     */
    @Override
    public PagingUtil songOfSingerId(Integer singerId, Integer currentPage, String word, Integer pageSize) {

        Integer totalCount = songMapper.songNumberOfSingerId(singerId, word);
        int start = 0;
        if (pageSize != null) {
            start = (currentPage - 1) * pageSize;
        }
        List<Song> data = songMapper.songOfSingerId(start, pageSize, singerId, word);
        int pageCount = 0;
        if (pageSize != null) {
            pageCount = (totalCount % pageSize == 0 ? (totalCount / pageSize) : (totalCount / pageSize) + 1);
        }
        PagingUtil pagingUtil = new PagingUtil(pageSize, totalCount, pageCount, currentPage, data);
        return pagingUtil;
    }


    @Override
    public List<Song> selectSongsBySingerId(Integer singerId) {
        return songMapper.songsBySingerId(singerId);
    }

    @Override
    public Song songOfSongId(Integer songId) {
        songMapper.selfIncreasingPlayCountOfSong(Long.valueOf(songId));
        return songMapper.songOfSongId(songId);
    }


    @Override
    public List<Song> likeSongSingerByKeyword(String name, Integer limit) {
        return songMapper.likeSongSingerByKeyword("%" + name + "%", limit);
    }

    @Override
    public List<Song> likeSongByKeyword(String name) {
        return songMapper.likeSongNameByKeyword(name);
    }

    @Override
    public List<Song> recentlySongList(Integer consumerId) {
        return songMapper.recentlySongList(consumerId);
    }

    @Override
    public boolean replaceRecentlySong(Integer consumerId, Integer songId) {
        return songMapper.replaceRecentlySong(consumerId, songId) > 0;
    }

    @Override
    public Response songRankingList(int number, int group) {
        // 调用数据库获取歌曲列表-根据歌曲收听次数字段降序排序
        List<Song> songs = songMapper.selectRankingOfSong(number);
        Optional<List<Song>> data = Optional.ofNullable(songs);
        if (!data.isPresent()) {
            return new Response<>(data, 0);
        }
        // 开始分组
        List<List<Song>> result = new ArrayList<>();
        if (group == 0) {
            result.add(data.get());
            return new Response<List<List<Song>>>(result, 1);
        }
        // 计算余数
        int remainder = songs.size() % group;
        // 计算组数
        int groupNumber = songs.size() / group;
        if (remainder > 0) {
            groupNumber++;
        }
        // 向每组添加歌曲
        for (int i = 0; i < groupNumber - 1; i++) {
            List<Song> item = new ArrayList<>(group);
            item = songs.subList((i * group), (i * group + group));
            result.add(item);
        }
        // 如果存在余数还需要添加多一组
        if (remainder > 0) {
            List<Song> item = new ArrayList<>(group);
            item = songs.subList(songs.size() - remainder, songs.size() - remainder + 1);
            result.add(item);
        }
        return new Response<List<List<Song>>>(result, result.size());
    }

    @Override
    public List<Song> randomSong() {
        // 数据查询 - 查询MySQL获取歌曲列表
        return songMapper.randomSong();
    }

    @Override
    public List<Song> randomSongByCache() {
        // 数据查询 - 查询Redis缓存的歌曲列表数据
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String cache = operations.get("randomSong");
        if(cache == null){
            log.info("randomSong缓存为空");
            return null;
        }
        // 数据封装 - 缓存的歌曲列表封装成java类
        return JSON.parseObject(cache, new TypeReference<List<Song>>() {});
    }

    @Override
    public List<Song> selectCollectSong(Long consumerId) {
        return songMapper.selectCollectSong(consumerId);
    }


    @Override
    public List<Integer> selectCollectSongId(Long consumerId) {
        List<Song> songs = songMapper.selectCollectSongId(consumerId);
        List<Integer> songIdList = new ArrayList<>();
        for (Song song : songs) {
            songIdList.add(song.getId());
        }
        return songIdList;
    }

    @Override
    public List<Song> selectSongsOfPlaylist(Long playlistId) {
        return songMapper.selectSongsOfPlaylist(playlistId);
    }

    @Override
    public List<Song> selectRankingOfSong(Integer limit) {
        if (limit == null) {
            limit = 50;
        }
        return songMapper.selectRankingOfSong(limit);
    }

    @Override
    public void uploadFile(HttpServletRequest request, MultipartFile file, MultipartFile pic) throws IOException {
        Song newSong = new Song();

        // 获取前端传来的参数并进行非空判断
        String singer = request.getParameter("singer");
        if (singer == null || singer.trim().isEmpty()) {
            throw new IllegalArgumentException("歌手名称不能为空");
        }
        singer = singer.trim();

        String name = request.getParameter("name");
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("歌曲名称不能为空");
        }
        name = name.trim();

        String introduction = request.getParameter("introduction");
        if (introduction == null || introduction.trim().isEmpty()) {
            introduction = ""; // 可以根据业务需求处理，这里设为空字符串
        } else {
            introduction = introduction.trim();
        }

        String lyric = request.getParameter("lyric");
        if (lyric == null || lyric.trim().isEmpty()) {
            lyric = ""; // 可以根据业务需求处理，这里设为空字符串
        } else {
            lyric = lyric.trim();
        }

        newSong.setSinger(singer);
        newSong.setName(name);
        newSong.setIntroduction(introduction);
        newSong.setCreateTime(new Date());
        newSong.setUpdateTime(new Date());
        newSong.setLyric(lyric);

        // 对文件进行非空判断
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("歌曲文件不能为空");
        }
        String url = fileUpload.upload(file);

        if (pic == null || pic.isEmpty()) {
            throw new IllegalArgumentException("歌曲图片不能为空");
        }
        String picUrl = fileUpload.upload(pic);

        newSong.setPic(picUrl);
        newSong.setUrl(url);

        insertSong(newSong);
    }

    @Override
    public Song selectSongById(Integer id ) {
        return  songMapper.selectSongById(id);
    }

    @Override
    public boolean updataSongPic(int id, MultipartFile pic) throws IOException {
       if(selectSongById(id)==null){
           throw new RuntimeException("参数错误");
       }
        String newPic = fileUpload.upload(pic);

        return songMapper.updateSongPic(id,newPic)>0;
    }


}
